package mi.payment.utils.print;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import mi.payment.MyApplication;
import mi.payment.R;
import mi.payment.ui.print.helper.PrintTransaction;
import mi.payment.ui.print.helper.TotalSettlementDetail;
import mi.payment.constants.Configs;
import mi.payment.constants.TransShortType;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.NetworkDataOperations;
import mi.payment.settings.NetworkParamSettings;
import mi.payment.settings.OfflineTransactionOperation;
import mi.payment.settings.OfflineTransactionSettings;
import mi.payment.settings.SalesSlipPrintSettings;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.settings.SettlementTransaction;
import mi.payment.settings.SettlementTransactionOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.SystemParamsSettings;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TerminalKeyManagementBean;
import mi.payment.settings.TransactionInputPwd;
import mi.payment.settings.TransactionInputPwdOperation;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.settings.TransactionOtherSettings;
import mi.payment.settings.TransactionSwitchOperation;
import mi.payment.settings.TransactionSwitchSetting;
import mi.payment.ui.print.helper.PrintCodeTicket;
import mi.payment.ui.print.helper.PrintSettlementTicket;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.NumberUtil;
import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * 打印签购单的实现类
 *
 * @author WL on 2016/11/19.
 */
public class DataPrinterKernel {

    private final String TAG = "DataPrinterKernel";

    private static final DataPrinterKernel instance = new DataPrinterKernel();

    private Context context;
    private IWoyouService printerService;

    private String smallTicketTail; // 自定义内容
    private boolean qrPrintSign = false; // 二维码小票是否打印签名栏（支付宝、微信）
    private boolean isPrintIPAndPort = Configs.getInstance().PRINT_IP_PORT();
    private boolean isPrintCpVersion;

    public void setCpVersion(boolean isPrintCpVersion) {
        this.isPrintCpVersion = isPrintCpVersion;
    }

    public boolean isQrPrintSign() {
        return qrPrintSign;
    }

    public void setQrPrintSign(boolean qrPrintSign) {
        this.qrPrintSign = qrPrintSign;
    }

    private DataPrinterKernel() {
        context = MyApplication.getInstance();
    }

    public static DataPrinterKernel INSTANCE() {
        return instance;
    }

    /**
     * 打印交易总计单
     */
    public void printTransactionSummary(List<PrintTransaction> list, final ICallback callback) {
        if (printerService == null) {
            return;
        }
        try {
            MerManagerSettings merManagerSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            byte[] b = new byte[]{0x1b, 0x45, 0x00};
            printerService.sendRAWData(b, null);
            // 1居中
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.transaction_totle) + "\n", "", 30, null);
            printerService.printTextWithFont(getString(R.string.transaction_totle_e) + "\n", "", 21, null);
            printerService.setAlignment(0, null);
            printerService.printTextWithFont("\n", "", 30, null);
            String shopName;
            String merchantName = merManagerSettings.getMerchantName();
            if (TextUtils.isEmpty(merchantName)) {
                shopName = "";
            } else {
                shopName = merchantName;
            }
            String shopNumber = merManagerSettings.getMerchantNum();
            if (TextUtils.isEmpty(shopNumber)) {
                shopNumber = "";
            }

            String terminalNumber = merManagerSettings.getTerminalNum();
            if (TextUtils.isEmpty(terminalNumber)) {
                terminalNumber = "";
            }

            printerService.printTextWithFont(getString(R.string.receipt_3_e) + shopName + "\n", "", 20, null);
            printerService.printTextWithFont(getString(R.string.receipt_4_e) + shopNumber + "\n" + getString(R.string.receipt_5_e) + terminalNumber + "\n", "", 20, null);
            printerService.setFontSize(19, null);
            printerService.printColumnsString(new String[]{getString(R.string.transaction_type), getString(R.string.number_of_pens), getString(R.string.total_amount)}, new int[]{14, 14, 14}, new int[]{1, 1, 1}, null);
            printerService.printTextWithFont("--------------------------------\n", "", 24, null);
            for (int i = 0; i < list.size(); i++) {
                printerService.setFontSize(20, null);
                String totalAmount = MoneyUtils.longCent2DoubleMoneyStr(list.get(i).totalAmount);
                printerService.printColumnsString(new String[]{list.get(i).type, list.get(i).total + "", totalAmount + ""}, new int[]{14, 14, 14}, new int[]{1, 1, 1}, null);
            }
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, null);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private String transMoneyValue(String str) {
        return new BigDecimal(str).movePointLeft(2).toPlainString();
    }

    /**
     * 交易明细
     */
    public void transactionDetail(List<PayDetail> transactionDetails, final ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            printerService.setAlignment(1, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x00}, null);
            printerService.printTextWithFont(getString(R.string.transaction_specification_list) + "\n", "", 30, null);
            printerService.printTextWithFont(getString(R.string.card_specification_list) + "\n", "", 21, null);
            printerService.setFontSize(20, null);
            printerService.printTextWithFont("\n", "", 30, null);
            printerService.printColumnsString(new String[]{getString(R.string.proof), getString(R.string.type), getString(R.string.card_number), getString(R.string.amount_of_money)}, new int[]{2, 1, 4, 2}, new int[]{1, 1, 1, 1}, null);
            printerService.setFontSize(14, null);
            printerService.printColumnsString(new String[]{getString(R.string.proof_e), getString(R.string.type_e), getString(R.string.card_number_e), getString(R.string.amount_of_money_e)}, new int[]{2, 1, 4, 2}, new int[]{1, 1, 1, 1}, null);
            printerService.printTextWithFont("------------------------------------------\n", "", 18, null);
            if (transactionDetails != null) {
                for (int i = 0; i < transactionDetails.size(); i++) {
                    PayDetail item = transactionDetails.get(i);
                    printerService.setFontSize(20, null);
                    byte[] b = {0x1b, 0x45, 0x00};
                    printerService.sendRAWData(b, null);
                    String amount = MoneyUtils.longCent2DoubleMoneyStr(item.amount);
                    String auth = item.authNo;
                    String card = NumberUtil.intercept(item.CardNo);
                    String type = "";
                    if (item.getTransPlatform() == 0) {
                        type = item.transType;
                    } else {
                        type = item.getTransPlatform() + "+" + item.getTransactionType();
                    }
                    type = TransShortType.type.get(type);
                    type = TextUtils.isEmpty(type) ? " " : type;
                    String voucher = item.voucherNo;
                    printerService.printColumnsString(
                            new String[]{voucher, type, card, amount},
                            new int[]{2, 1, 4, 2},
                            new int[]{1, 1, 1, 1},
                            null
                    );
                }
            }
            printerService.setAlignment(0, null);
            printerService.printTextWithFont("------------------------------------------\n", "", 18, null);
            printerService.printTextWithFont(getString(R.string.detail_em) + "\n", "", 14, null);
            printerService.printTextWithFont(getString(R.string.detail_em1) + "\n", "", 14, null);
            printerService.printTextWithFont(getString(R.string.detail_em2) + "\n", "", 14, null);
            printerService.printTextWithFont(getString(R.string.detail_em4) + "\n", "", 14, null);
            printerService.printTextWithFont(getString(R.string.detail_em5) + "\n", "", 14, null);
            printSmallTicketTail(printerService, callback, 14, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 商户信息打印
     */
    public void printMerchantInfo(String packageName, String version, final ICallback callback) {
        if (printerService == null) return;
        try {
            MerManagerSettings merManagerSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.merchant_params) + "******" + "\n", "", 30, null);

            printerService.setAlignment(0, null);
            String merchantName;
            String name = merManagerSettings.getMerchantName();
            if (TextUtils.isEmpty(name)) {
                merchantName = " ";
            } else {
                merchantName = name;
            }
            printerService.printTextWithFont(getString(R.string.merchant_params1) + merchantName + "\n", "", 24, null);
            String merchantNum;
            String num = merManagerSettings.getMerchantNum();
            if (TextUtils.isEmpty(num)) {
                merchantNum = " ";
            } else {
                merchantNum = num;
            }
            printerService.printTextWithFont(getString(R.string.merchant_params2) + merchantNum + "\n", "", 24, null);
            String terminalNum;
            String terminalNo = merManagerSettings.getTerminalNum();
            if (TextUtils.isEmpty(terminalNo)) {
                terminalNum = " ";
            } else {
                terminalNum = terminalNo;
            }
            printerService.printTextWithFont(getString(R.string.merchant_params3) + terminalNum + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.merchant_params4) + packageName + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.merchant_params5) + version + "\n", "", 24, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 版本信息打印
     */
    public void printVersionInfo(String version, final ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.version_name_info) + "******" + "\n", "", 30, null);
            printerService.setAlignment(0, null);
            String apVersion = isPrintCpVersion ? "CJZF-SM-V01-20180409" : version;
            printerService.printTextWithFont(getString(R.string.merchant_params5) + apVersion + "\n", "", 24, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 商户信息打印
     */
    public void printOtherInfo(final ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            TerminalKeyDataOperations mTerminalKeyDataOperations = TerminalKeyDataOperations.getInstance();
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.other_info) + "******" + "\n", "", 30, null);

            printerService.setAlignment(0, null);

            printerService.printTextWithFont(getString(R.string.terminal_key_index) + "：" + mTerminalKeyDataOperations.getTerminalKeyIndex() + "\n", "", 24, null);
            if (!Configs.getInstance().HIDE_SET_DES_ALGORITHM()) {
                if (mTerminalKeyDataOperations.getDes().equals(TerminalKeyManagementBean.SINGLE_DES)) {
                    printerService.printTextWithFont(getString(R.string.key_algorithms) + "：" + getString(R.string.single_des) + "\n", "", 24, null);
                } else if (mTerminalKeyDataOperations.getDes().equals(TerminalKeyManagementBean.THREE_DES)) {
                    printerService.printTextWithFont(getString(R.string.key_algorithms) + "：" + getString(R.string.three_des) + "\n", "", 24, null);
                }
            }
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 交易控制打印
     */
    public void printTransactionInfo(final ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            TransactionSwitchSetting transactionSwitchSetting = TransactionSwitchOperation.getInstance().getTransactionSwitchSetting();
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.transaction_setting_info) + "******" + "\n", "", 30, null);

            printerService.setAlignment(0, null);
            String str = (transactionSwitchSetting.isConsumption()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.consume_im_title) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isConsumptionRevoke()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.cancellation_title) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isReturnGoods()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.return_title) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isQueryBalance()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.balance_query) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isFieldAuth()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.traditional_transaction_pre_auth) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isFieldAuthRevoke()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.traditional_transaction_pre_auth_cancel) + "：" + str + "\n", "", 24, null);
            str = (transactionSwitchSetting.isFieldAuthReq()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.traditional_transaction_pre_authorization_complete_request) + "：" + str + "\n", "", 24, null);
            if (Configs.getInstance().HIDE_PRE_AUTHORIZATION_NOTICE()) {
                // 隐藏预授权通知
            } else {
                str = (transactionSwitchSetting.isFieldAuthCompleteRevocationNotice()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
                printerService.printTextWithFont(getString(R.string.traditional_transaction_pre_authorization_complete) + "：" + str + "\n", "", 24, null);
            }
            str = (transactionSwitchSetting.isFieldAuthCompleteRevocation()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.traditional_transaction_pre_auth_complete_cancel) + "：" + str + "\n", "", 24, null);

            printerService.printTextWithFont("\n", "", 24, null);

            TransactionInputPwd transactionInputPsd = TransactionInputPwdOperation.getInstance().getTransactionInputPwd();
            str = (transactionInputPsd.isConsumptionRevokePsd()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.void_transaction_password) + "：" + str + "\n", "", 24, null);
            str = (transactionInputPsd.isFieldAuthRevokePsd()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.cancel_transaction_password) + "：" + str + "\n", "", 24, null);
            str = (transactionInputPsd.isFieldAuthCompleteRevokePsd()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.complete_void_transaction_password) + "：" + str + "\n", "", 24, null);
            str = (transactionInputPsd.isFieldAuthCompleteReqPsd()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.auth_complete_transaction_password) + "：" + str + "\n", "", 24, null);

            printerService.printTextWithFont("\n", "", 24, null);

            SettlementTransaction settlementTransaction = SettlementTransactionOperation.getInstance().getSettlementTransaction();
            str = (settlementTransaction.isAutomaticSignOut()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.is_settlement_transaction_finish_exit) + "：" + str + "\n", "", 24, null);

            printerService.printTextWithFont("\n", "", 24, null);

            OfflineTransactionSettings offlineTransactionSettings = OfflineTransactionOperation.getInstance().getOfflineTransactionSettings();
            printerService.printTextWithFont(getString(R.string.offline_push_number1) + "：" + offlineTransactionSettings.getOfflinePushCount() + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.automatic_sending_count1) + "：" + offlineTransactionSettings.getAutomaticallyNumber() + "\n", "", 24, null);
            str = (offlineTransactionSettings.isSmallPaymentWay()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.support_small_payment_way) + "：" + str + "\n", "", 24, null);

            printerService.printTextWithFont("\n", "", 24, null);

            TransactionOtherSettings transactionOtherSettings = TransactionOtherOperation.getInstance().getTransactionOtherSettings();
            str = (transactionOtherSettings.getInputDirectorPsd()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.is_cancel_the_refund_transaction_input_password) + "：" + str + "\n", "", 24, null);
            str = (transactionOtherSettings.getInputCardNum()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.is_allow_manual_input_card_number) + "：" + str + "\n", "", 24, null);
            str = (transactionOtherSettings.getDefaultTransaction()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.default_transaction_select) + "：" + str + "\n", "", 24, null);

            printerService.printTextWithFont(getString(R.string.max_refund_amt) + getString(R.string.yuan) + "：" + MoneyUtils.longCent2DoubleMoneyStr(transactionOtherSettings.getMaximumReturnAmount()) + "\n", "", 24, null);

            str = (transactionOtherSettings.isICCardShowCardNumber()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.ic_show_card_number) + "：" + str + "\n", "", 24, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * 系统参数设置
     */
    public void printSystemParams(final ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            SystemParamsSettings systemParamsSettings = SystemParamsOperation.getInstance().getSystemParamsSettings();
            SalesSlipPrintSettings salesSlipPrintSettings = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings();
            String str;
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.system_settings_info) + "******" + "\n", "", 30, null);
            printerService.setAlignment(0, null);
            printerService.printTextWithFont(getString(R.string.serial_number_starting) + "：" + systemParamsSettings.getCurrentSerialNum() + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.batch_number_start) + "：" + systemParamsSettings.getBatchNumStart() + "\n", "", 24, null);
            str = (salesSlipPrintSettings.isAcquiringBankPrintChinese()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.printed_in_chinese) + "：" + str + "\n", "", 24, null);
            str = (salesSlipPrintSettings.issuingBankPrintChinese()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.issuing_bank_printing_hinese) + "：" + str + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.print_number_setting) + "：" + salesSlipPrintSettings.getPrintReceiptSingleNum() + "\n", "", 24, null);
            str = (salesSlipPrintSettings.isSalesSlipPrintEnglish()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.invoice_printing_print_english) + "：" + str + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.correct_number_of_retransmissions) + "：" + systemParamsSettings.getCorrectFrequency() + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.maximum_transaction) + "：" + systemParamsSettings.getTransactionNumber() + "\n", "", 24, null);

            if (Configs.getInstance().MINUS_PRINT()) {
                str = (systemParamsSettings.isPrintNegative()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
                printerService.printTextWithFont(getString(R.string.the_transaction_minus_print) + "：" + str + "\n", "", 24, null);
            }
            switch (systemParamsSettings.getNonConnection()) {
                case 0:
                    printerService.printTextWithFont(getString(R.string.non_access_switch) + "：" + getString(R.string.non_access_switch1) + "\n", "", 24, null);
                    break;
                case 1:
                    printerService.printTextWithFont(getString(R.string.non_access_switch) + "：" + getString(R.string.non_access_switch2) + "\n", "", 24, null);
                    break;
                default:
                    printerService.printTextWithFont(getString(R.string.non_access_switch) + "\n", "", 24, null);
                    break;
            }
            str = (systemParamsSettings.isStateSecret()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.whether_to_support_state_secrets) + "：" + str + "\n", "", 24, null);
            str = (systemParamsSettings.isShieldAuthorizationCard()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.pre_license_card_number) + "：" + str + "\n", "", 24, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通讯参数打印
     */
    public void printCommunicationInfo(final ICallback callback) {
        if (printerService == null) {
            return;
        }
        try {
            NetworkParamSettings networkParamSettings = NetworkDataOperations.getInstance().getNetworkParamSettings();
            String str;
            printerService.enterPrinterBuffer(true);
            printerService.printText("\n", callback);
            printerService.setAlignment(1, null);
            printerService.printTextWithFont(getString(R.string.evm_params) + "\n", "", 42, null);
            printerService.printTextWithFont("******" + getString(R.string.communication_params_info) + "******" + "\n", "", 30, null);

            printerService.setAlignment(0, null);
            printerService.printTextWithFont(getString(R.string.tpdu1) + "：" + networkParamSettings.getTPdu() + "\n", "", 24, null);

            if (isPrintIPAndPort) {
                printerService.printTextWithFont(getString(R.string.host_ip_address1) + "：" + networkParamSettings.getHostIpAddress() + "\n", "", 24, null);
                printerService.printTextWithFont(getString(R.string.host_port1) + "：" + networkParamSettings.getHostPort() + "\n", "", 24, null);
            }

            str = (networkParamSettings.isAutomaticGetIp()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.automatically_obtain_ip) + "：" + str + "\n", "", 24, null);

            if (isPrintIPAndPort) {
                printerService.printTextWithFont(getString(R.string.backup_ip_address1) + "：" + networkParamSettings.getSpareHostIpAddress() + "\n", "", 24, null);
                printerService.printTextWithFont(getString(R.string.backup_port1) + "：" + networkParamSettings.getSpareHostPort() + "\n", "", 24, null);
            }

            if (Configs.getInstance().SUPPORT_THIRD_HOST()) {
                if (isPrintIPAndPort) {
                    printerService.printTextWithFont(getString(R.string.third_server_ip1) + "：" + networkParamSettings.getThirdServerIpAddress() + "\n", "", 24, null);
                    printerService.printTextWithFont(getString(R.string.third_server_port1) + "：" + networkParamSettings.getThirdServerPort() + "\n", "", 24, null);
                }
            }

            printerService.printTextWithFont(getString(R.string.communication_timeout1) + "：" + networkParamSettings.getCommunicationTimeout() + "\n", "", 24, null);
            printerService.printTextWithFont(getString(R.string.deals_heavy_dial_number1) + "：" + networkParamSettings.getTransactionRepeatNum() + "\n", "", 24, null);
            switch (networkParamSettings.getConnectionMode()) {
                case 0:
                    printerService.printTextWithFont(getString(R.string.placement1) + "：" + getString(R.string.short_placement) + "\n", "", 24, null);
                    break;
                case 1:
                    printerService.printTextWithFont(getString(R.string.placement1) + "：" + getString(R.string.long_placement) + "\n", "", 24, null);
                    break;
                default:
                    printerService.printTextWithFont(getString(R.string.placement1) + "\n", "", 24, null);
                    break;
            }
            switch (networkParamSettings.getNetworkDefaultConfiguration()) {
                case 1:
                    printerService.printTextWithFont(getString(R.string.default_network_configuration1) + "：" + getString(R.string.default_network1) + "\n", "", 24, null);
                    break;
                case 2:
                    printerService.printTextWithFont(getString(R.string.default_network_configuration1) + "：" + getString(R.string.default_network2) + "\n", "", 24, null);
                    break;
                default:
                    printerService.printTextWithFont(getString(R.string.default_network_configuration1) + "\n", "", 24, null);
                    break;
            }
            str = (networkParamSettings.isNetworkInterventionFunction()) ? (getString(R.string.support) + "") : (getString(R.string.unsuppot) + "");
            printerService.printTextWithFont(getString(R.string.internet_access_functions) + "：" + str + "\n", "", 24, null);

            str = (networkParamSettings.isDns()) ? (getString(R.string.yes) + "") : (getString(R.string.no) + "");
            printerService.printTextWithFont(getString(R.string.dns_enable) + "：" + str + "\n", "", 24, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 24, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化打印服务连接
     */
    public void init() {
        if (printerService == null) {
            Intent intent = new Intent();
            intent.setPackage("woyou.aidlservice.jiuiv5");
            intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
            context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            printerService = IWoyouService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            printerService = null;
        }

    };

    /**
     * 打印查询凭证单
     */
    public void printQueryVoucherNo(PayDetail payDetail, ICallback callback) {
        if (printerService == null) return;
        try {
            printerService.enterPrinterBuffer(true);
            printerService.printerInit(callback);

            // 打印查询凭证号
            printerService.setAlignment(1, null);
            printerService.setFontSize(48, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x45, 0x01}, null);
            printerService.printTextWithFont(getString(R.string.query_voucherno) + "\n", "", 40, null);

            printerService.setFontSize(16, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x12}, null);
            printerService.printTextWithFont("-----------------------------------------------", "", 16, null);
            printerService.setAlignment(0, null);
            printerService.printTextWithFont(getString(R.string.bussines_receipt) + "\n", "", 18, null);
            printerService.setAlignment(1, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x12}, null);
            printerService.printTextWithFont("-----------------------------------------------", "", 16, null);

            // 打印商户名称
            printerService.setFontSize(24, null);
            printerService.setAlignment(0, null);

            String merchantName = " ";
            if (!TextUtils.isEmpty(payDetail.merchantName)) {
                merchantName = payDetail.merchantName;
            }
            printerService.printTextWithFont(getString(R.string.receipt_3) + merchantName + "\n", "", 24, null);

            // 打印商户号
            String merchantNo = " ";
            if (!TextUtils.isEmpty(payDetail.merchantNo)) {
                merchantNo = payDetail.merchantNo;
            }
            printerService.printTextWithFont(getString(R.string.receipt_4) + merchantNo + "\n", "", 24, null);

            // 打印终端号
            String terminalNo = " ";
            if (!TextUtils.isEmpty(payDetail.terminalNo)) {
                terminalNo = payDetail.terminalNo;
            }

            printerService.printColumnsString(new String[]{getString(R.string.receipt_5) + terminalNo, getString(R.string.receipt_20) + payDetail.operatorNo}, new int[]{7, 5}, new int[]{0, 2}, null);

            printerService.setAlignment(1, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x12}, null);
            printerService.printTextWithFont("-----------------------------------------------" + "\n", "", 16, null);

            printerService.setAlignment(0, null);
            printerService.printTextWithFont(String.format(getString(R.string.make7), "") + "\n", "", 24, null);

            printerService.setAlignment(0, null);
            printerService.printTextWithFont(getString(R.string.tran_swept_payment) + "\n", "", 40, null);


            // 打印批次号和凭证号
            String receipt_10 = getString(R.string.receipt_10);
            String receipt_15 = getString(R.string.receipt_15);
            printerService.printColumnsString(new String[]{receipt_10 + payDetail.BathNo, receipt_15 + payDetail.voucherNo}, new int[]{5, 5}, new int[]{0, 2}, null);

            // 打印交易时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            printerService.printTextWithFont(String.format(getString(R.string.make11), "") + dateString + "\n", "", 24, null);
            // 打印说明
            printerService.printTextWithFont("    " + getString(R.string.receipt_22) + "\n", "", 24, null);

            printerService.setAlignment(1, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x12}, null);
            printerService.printTextWithFont("-----------------------------------------------\n", "", 16, null);
            printerService.setFontSize(16, null);

            String receipt_23 = getString(R.string.receipt_23);
            printerService.setAlignment(0, null);
            printerService.sendRAWData(new byte[]{0x1B, 0x45, 0x01}, null);
            printerService.printTextWithFont(receipt_23 + "\n", "", 16, null);

            printerService.setAlignment(1, null);
            printerService.printBarCode(payDetail.getVoucherNo(), 8, 100, 3, 0, null);

            printerService.sendRAWData(new byte[]{0x1B, 0x33, 0x10}, null);
            printerService.setAlignment(1, null);
            printerService.printTextWithFont("\n-----------------------------------------------\n", "", 16, null);
            printerService.printTextWithFont("\n- - - - - - - - - - - - - - - - - - - - - - - -\n", "", 16, null);
            printSmallTicketTail(printerService, callback, 18, getSmallTicketTail());
            printerService.printTextWithFont("\n\n\n", "", 20, callback);
            printerService.exitPrinterBufferWithCallback(true, callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printBankTicket(PayDetail payDetail, final ICallback callback, int pageNum, boolean isAgain) throws Exception {
        BankTicketPrinter printer = new BankTicketPrinter(context, printerService);
        String smallTicketTail = getSmallTicketTail();
        printer.setSmallTicketTail(smallTicketTail);
        printer.printBankTicket(payDetail, callback, pageNum, isAgain);
    }

    public String getSmallTicketTail() {
        return "Power by MYP1 Commerce Sdn Bhd";
    }

    public void setSmallTicketTail(String info) {
        this.smallTicketTail = info;
    }

    /**
     * 打印小票底部信息 自定义内容 or 设备名称、AP版本号、设配SN号
     */
    public void printSmallTicketTail(IWoyouService printerService, ICallback callback, int size, String info) throws RemoteException {
        printerService.printTextWithFont("\n", "", 14, callback);
        printerService.printTextWithFont(info + "\n", "", size, null);
        printerService.printerInit(null);
    }

    public IWoyouService getPrinterService() {
        return printerService;
    }

    public int updatePrinterState() throws RemoteException {
        if (printerService == null) return -1;
        return printerService.updatePrinterState();
    }

    private String getString(int id) {
        return context.getString(id);
    }


    /**
     * 打印二维码小票
     */
    public void printQRCodeTicket(PayDetail payDetail, boolean isAgain, ICallback callback, int pageNum, boolean printBarcode) throws Exception {
        PrintCodeTicket ticket = new PrintCodeTicket();
        ticket.printCodeTicket(payDetail, isAgain, pageNum, printBarcode, callback);
    }

    /**
     * 结算总计单
     */
    public void printTotalSettlement(TotalSettlementDetail detail, final ICallback callback) throws Exception {
        PrintSettlementTicket ticket = new PrintSettlementTicket();
        ticket.printCodeTotalSettlement(detail, callback);
    }


}
